package net.dgg.zz.credential.qualificationTransfer.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.baseCredential.entity.BaseCredential;
import net.dgg.zz.credential.certificateSpecialty.entity.CertificateSpecialty;
import net.dgg.zz.credential.certificateSpecialty.service.CertificateSpecialtyService;
import net.dgg.zz.credential.qualificationTransfer.dao.QualificationTransferDao;
import net.dgg.zz.credential.qualificationTransfer.dao.QualificationTransferRecordDao;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransfer;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransferRecord;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransferVo;
import net.dgg.zz.credential.qualificationTransfer.entity.ReviewRejectedVo;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import net.dgg.zz.credential.storageCapacity.service.StorageCapacityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class QualificationTransferService extends BaseService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private QualificationTransferDao qualificationTransferDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private BaseCredentialDao credentialDao;
    @Autowired
    private QualificationTransferRecordDao transferRecordDao;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private CertificateSpecialtyService certificateSpecialtyService;
    @Autowired
    private StorageCapacityService storageCapacityService;

    /*
     * @Author zsx
     * @Date 2018-08-30 09:08:02
     * @Description 分页查询资质转让待审核数据
     * @param params
     * @return  List<QualificationTransferVo>
     */
    public List<QualificationTransferVo> queryPendingAuditWithPage(Map<String, Object> params) {
        params.put("auditerStatus", CredentialConstant.TRANSFER_CHECK_PENDING);
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("currentAuditerId", sessionManager.getCurrentUser().getId());
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "asc");
            params.put("orderColumn", "qt.create_time");
        }
        List<QualificationTransferVo> list = qualificationTransferDao.queryPendingAuditWithPage(params);
        String[] column = {"applicationScope", "certificateArea", "areaProvince", "overdueStatus", "certificateLevel"};
        return translateUtil.translateList(column, list);
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 03:08:27
     * @Description 分页查询审核驳回数据
     * @param null
     * @return null
     */
    public List<QualificationTransferVo> queryRejectedRecordWithPage(Map<String, Object> params) {
        params.put("auditerStatus", CredentialConstant.TRANSFER_REJECTED_AUDIT);
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("currentAuditerId", sessionManager.getCurrentUser().getId());
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "asc");
            params.put("orderColumn", "qt.create_time");
        }
        List<QualificationTransferVo> list = qualificationTransferDao.queryAuditRecordWithPage(params);
        String[] column = {"applicationScope", "certificateArea", "areaProvince", "certificateLevel"};
        return translateUtil.translateList(column, list);
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 04:08:56
     * @Description 分页查询已转让资质记录
     * @param params
     * @return List<QualificationTransferVo>
     */
    public List<QualificationTransferVo> queryTransferredRecordithPage(Map<String, Object> params) {
        params.put("auditerStatus", CredentialConstant.TRANSFER_PASS_AUDIT);
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("currentAuditerId", sessionManager.getCurrentUser().getId());
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "asc");
            params.put("orderColumn", "qt.create_time");
        }
        List<QualificationTransferVo> list = qualificationTransferDao.queryAuditRecordWithPage(params);
        String[] column = {"applicationScope", "certificateArea", "areaProvince", "certificateLevel"};
        return translateUtil.translateList(column, list);
    }


    /*
     * @Author zsx
     * @Date 2018-08-30 02:08:22
     * @Description 根据id查询详情
     * @param id
     * @return Map<String,Object>
     */
    public Map<String, Object> selectTransferDetails(Long id) {
        return qualificationTransferDao.selectTransferDetailsById(id);
    }

    /*
     * @Author zsx
     * @Date 2018-09-03 08:09:47
     * @Description 查询需要导出的资质审核驳回记录
     * @param params
     * @return List<QualificationTransferVo>
     */
    public List<ReviewRejectedVo> selectRejectedRecord(Map<String, Object> params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("currentAuditerId", sessionManager.getCurrentUser().getId());
        }
        params.put("auditerStatus", CredentialConstant.TRANSFER_REJECTED_AUDIT);
        List<ReviewRejectedVo> rejectedVos = qualificationTransferDao.selectRejectedRecord(params);
        String[] column = {"applicationScope", "certificateArea", "areaProvince", "certificateLevel"};
        return translateUtil.translateList(column, rejectedVos);
    }

    /*
     * @Author zsx
     * @Date 2018-09-03 09:09:01
     * @Description 查询需要导出的资质审核通过记录
     * @param params
     * @return List<>
     */
    public List<QualificationTransferVo> selectTransferredRecord(Map<String, Object> params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("currentAuditerId", sessionManager.getCurrentUser().getId());
        }
        params.put("page", null);
        params.put("limit", null);
        params.put("orderDir", "asc");
        params.put("orderColumn", "qt.create_time");
        params.put("auditerStatus", CredentialConstant.TRANSFER_PASS_AUDIT);
        List<QualificationTransferVo> list = qualificationTransferDao.queryAuditRecordWithPage(params);
        String[] column = {"applicationScope", "certificateArea", "areaProvince", "certificateLevel"};
        return translateUtil.translateList(column, list);
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 04:52:59
     * @Description 修改资质审核人
     * @param id 资质转让id
     * @param nextReviewer 审核人
     * @param remark 备注
     * @return DggRestResponse
     */
    @Transactional
    public Map<String, Object> updateAuditor(Long id, Long nextReviewer, String remark) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
            return map;
        }
        Map<String, Object> restMap = selectTransferDetails(id);
        if (!user.getId().equals(restMap.get("currentAuditerId"))) {
            map.put("status", false);
            map.put("msg", "亲！你不是当前审核人哦");
            return map;
        }
        if (nextReviewer.equals(user.getId())) {
            return map;
        }
        //获取审核人
        UserEntity reviewer = userService.findUserById(nextReviewer);
        if (null == reviewer) {
            map.put("status", false);
            map.put("msg", "审核人不存在");
            return map;
        }
        QualificationTransfer transfer = qualificationTransferDao.selectByPrimaryKey(id);
        if (StringUtils.isNotEmpty(remark)) {
            transfer.setRemarks(remark);
        }
        Boolean status = updateReviewer(transfer, user, reviewer);
        if (!status) {
            map.put("status", false);
            map.put("msg", "修改审核人失败");
        }
        //保存日志
        BaseCredential credential = credentialDao.selectByPrimaryKey(transfer.getBaseId());
        SystemRecord record = new SystemRecord();
        record.setSource("4");
        record.setOperateType("34");
        record.setWorkTableName("zz_qualification_transfer_record，zz_qualification_transfer，zz_base_credential");
        record.setWorkId(transfer.getId());
        record.setCertificateCode(credential.getCertificateNo());
        record.setSignOrgId(credential.getSignOrgId());
        record.setSignOrgName(credential.getSignOrgName());
        record.setCertificateType(CredentialConstant.ZZ_CREDENTIAL);
        record.setRemarks("资质转让：" + credential.getCertificateNo() + "变更审核人 || 变更人备注：" + remark);
        systemRecordService.save(record);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 08:08:31
     * @Description 更新审核
     * @param params
     * @return Map<String, Object>
     */
    @Transactional
    public Map<String, Object> updateAuditStatus(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
            return map;
        }
        Map<String, Object> restMap = selectTransferDetails(Long.parseLong(params.get("id").toString()));
        if (!user.getId().equals(restMap.get("currentAuditerId"))) {
            map.put("status", false);
            map.put("msg", "亲！你不是当前审核人哦");
            return map;
        }
        QualificationTransfer transfer = qualificationTransferDao.selectByPrimaryKey(Long.parseLong(params.get("id").toString()));
        //判断是通过还是驳回
        String auditStatus = (String) params.get("auditStatus");
        //审核通过 做对应的处理
        if (auditStatus.equals(CredentialConstant.TRANSFER_PASS_AUDIT)) {
            //变更下一级审核人
            if (transfer.getReviewProgression() - transfer.getCurrentReviewProgression() > 1) {
                if (StringUtils.isEmpty(params.get("nextReviewer"))) {
                    map.put("status", false);
                    map.put("msg", "下一级审核人不能为空");
                    return map;
                }
                UserEntity reviewer = userService.findUserById(Long.parseLong(params.get("nextReviewer").toString()));
                if (null == reviewer) {
                    map.put("status", false);
                    map.put("msg", "下一级审核人不存在");
                    return map;
                }
                transfer.setCurrentReviewProgression(transfer.getCurrentReviewProgression() + 1);
                //更新下级审核人
                updateReviewer(transfer, user, reviewer);
                //添加审核记录
                saveTransferRecord(user, params);
            } else {
                //更新资质转让状态
                transfer.setAuditerStatus(CredentialConstant.TRANSFER_PASS_AUDIT);
                transfer.setCurrentReviewProgression(transfer.getCurrentReviewProgression() + 1);
                updateReviewer(transfer, user, null);
                //更新资质状态
                updateBaseCredentialStatus(transfer.getBaseId(), CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FIVE, user);
                //添加审核记录
                saveTransferRecord(user, params);
                //修改匹配量
                List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(transfer.getBaseId());
                if (StringUtils.isNotEmpty(certificateSpecialties) && certificateSpecialties.size() > 0) {
                    List<String> codes = new ArrayList<>();
                    for (CertificateSpecialty certificateSpecialty : certificateSpecialties) {
                        codes.add(certificateSpecialty.getCertificateCode());
                    }
                    // 查询以前绑定的基本类型的信息
                    List<StorageCapacity> storageCapacitysByCodes = storageCapacityService.findStorageCapacitysByCodes(codes);
                    //匹配量减1
                    for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                        storageCapacitysByCode.setMatchNumbers(storageCapacitysByCode.getMatchNumbers() - 1);
                    }
                    storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                }
            }
            //推送消息
            try {
                String[] msgs = new String[]{transfer.getScOrderNo(), DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss)};
                List<UserEntity> users = new ArrayList();
                users.add(userService.findUserById(transfer.getCreaterId()));
                commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZZ_TRANSFER_THROUGH");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } else if (auditStatus.equals(CredentialConstant.TRANSFER_REJECTED_AUDIT)) {
            //更新资质转让状态
            transfer.setAuditerStatus(CredentialConstant.TRANSFER_REJECTED_AUDIT);
            //transfer.setCurrentReviewProgression(transfer.getCurrentReviewProgression() + 1);
            updateReviewer(transfer, user, null);
            //更新资质状态
            updateBaseCredentialStatus(transfer.getBaseId(), CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE, user);
            //添加审核记录
            saveTransferRecord(user, params);
            //推送消息
            try {
                String[] msgs = new String[]{transfer.getScOrderNo(), DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss)};
                List<UserEntity> users = new ArrayList();
                users.add(userService.findUserById(transfer.getCreaterId()));
                commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZZ_TRANSFER_REJECTED");
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        //日志
        BaseCredential credential = credentialDao.selectByPrimaryKey(transfer.getBaseId());
        SystemRecord record = new SystemRecord();
        record.setSource("4");
        record.setOperateType("53");
        record.setWorkTableName("zz_qualification_transfer_record，zz_qualification_transfer，zz_base_credential");
        record.setWorkId(transfer.getId());
        record.setCertificateCode(credential.getCertificateNo());
        record.setSignOrgId(credential.getSignOrgId());
        record.setSignOrgName(credential.getSignOrgName());
        record.setCertificateType(CredentialConstant.ZZ_CREDENTIAL);
        record.setRemarks("资质转让：" + credential.getCertificateNo() + "审核 || 审核人备注：" + params.get("remark").toString());
        systemRecordService.save(record);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 09:08:15
     * @Description  修改审核人
     * @param transfer 资质转让对象
     * @param user 修改人
     * @param reviewer 下一级审核人信息
     * @return Boolean
     */
    private Boolean updateReviewer(QualificationTransfer transfer, UserEntity user, UserEntity reviewer) {
        if (null != reviewer) {
            transfer.setCurrentAuditerId(reviewer.getId());
            transfer.setCurrentAuditerName(reviewer.getRealName() + reviewer.getLoginName());
            transfer.setCurrentAuditerOrgId(reviewer.getOrgId());
            Map org = cmsService.findOrg(reviewer.getOrgId());
            if (null != org) {
                transfer.setCurrentAuditerOrgName(org.get("name").toString());
            }
        }
        this.updateOpt(transfer, user);
        int count = qualificationTransferDao.updateByPrimaryKeySelective(transfer);
        return count > 0;
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 11:08:40
     * @Description 保存审核记录
     * @param user 修改人实体
     * @param params
     * @return null
     */
    private void saveTransferRecord(UserEntity user, Map<String, Object> params) {
        QualificationTransferRecord record = new QualificationTransferRecord();
        record.setId(DggKeyWorker.nextId());
        record.setQualificationTransferId(Long.parseLong(params.get("id").toString()));
        record.setGeneralType(params.get("auditStatus").toString());
        record.setRemarks(params.get("remark") == null ? "" : params.get("remark").toString());
        record.setOperaterId(user.getId());
        record.setOperaterName(user.getRealName() + user.getLoginName());
        record.setOperaterOrgId(user.getOrgId());
        Map org = cmsService.findOrg(user.getOrgId());
        if (null != org) {
            record.setOperaterOrgName(org.get("name").toString());
        }
        record.setOperateTime(new Date());
        transferRecordDao.insertSelective(record);
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 10:08:26
     * @Description 更新资质状态
     * @param id 资质id
     *@param status 状态
     * @return void
     */

    private void updateBaseCredentialStatus(Long id, String status, UserEntity user) {
        BaseCredential credential = credentialDao.selectByPrimaryKey(id);
        credential.setCertificateStatus(status);
        this.updateOpt(credential, user);
        credentialDao.updateByPrimaryKeySelective(credential);
    }

    /*
     * @Author zsx
     * @Date 2018-09-06 06:09:18
     * @Description 根据资质转让id查询资质转让记录
     * @param transferId 资质转让id
     * @return List<QualificationTransferRecord
     */
    public List<QualificationTransferRecord> findRecordDetails(Long transferId) {
        List<QualificationTransferRecord> records = transferRecordDao.selectByQualificationTransferId(transferId);
        String[] column = {"generalType"};
        return translateUtil.translateList(column, records);
    }


}
